<template>
<!-- 包括页头、检索框、页尾以及登录注册等基本功能 -->
    <a-layout style="min-height: 100vh">
        <a-layout :style="{
            backgroundImage: 'url(' + backGroundImg + ')',
            backgroundRepeat: 'no-repeat', backgroundSize: '1600px 200px'
        }" style="background-color: #fff;">
            <a-layout-header style="background: transparent; padding: 0; margin-bottom: 20px;">
                <div style="display: flex;">
                    <div>
                        <img src="@/assets/logo-no-background.png" style="height: 60px;" @click="$router.push('/homepage_demo' + '?randomId=' + Math.random())" />
                    </div>
                    <div v-if="!login" style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-button style="background: transparent; color: white" @click="onLoginShow">
                            <template #icon><user-outlined style="color: white"/></template>
                            登录
                        </a-button>
                    </div>
                    <div v-else style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-dropdown>
                            <a-button style="background: transparent; color: white">
                                <user-outlined style="color: white"/>
                                {{ $store.state.username }}
                                <DownOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="onMenuClick">
                                    <a-menu-item key="settings">
                                        <strong>设置</strong>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="favorite">
                                        <strong>收藏</strong>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="interest">
                                        <strong>关注列表</strong>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="logout">
                                        <strong>退出登录</strong>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
                <hr class="custom-divider" />
            </a-layout-header>
            <a-layout-content>
                <div style="margin-top: 30px; margin-left: 420px">
                    <a-select defaultValue="title" :options="searchOptions" v-model:value="searchField" size="large" style="width: 80px" />
                    <a-input v-model:value="searchQuery" placeholder="请输入检索词" size="large" style="width: 580px; margin-left: 10px" />
                    <a-button type="primary" size="large" style="width: 100px; margin-left: 10px" @click="onSearch">
                        <template #icon><SearchOutlined /></template>
                        检索
                    </a-button>
                    <span style="color: white; margin-left: 10px ;cursor: pointer" @click="$router.push('/advancedSearch_demo')">高级检索></span>
                </div>
                <a-modal v-model:visible="loginShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">欢迎登录</div>
                            <a-form
                                    :model="loginForm"
                                    name="normal_login"
                                    class="login-form"
                                    style="margin-top: 20px"
                                    @finish="onLoginFinish"
                            >
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请输入账号' }]"
                                >
                                    <a-input v-model:value="loginForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请输入密码' }]"
                                >
                                    <a-input-password v-model:value="loginForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-form-item name="remember" no-style>
                                        <a-checkbox v-model:checked="loginForm.remember">自动登录</a-checkbox>
                                    </a-form-item>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-button :disabled="disabled" type="primary" html-type="submit" class="login-form-button" style="width: 100%">
                                        登录
                                    </a-button>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
                                        <a href="">注册新用户</a>
                                        <a class="login-form-forgot" href="">忘记密码</a>
                                    </div>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
                <a-modal v-model:visible="registerShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">注册账号</div>
                            <a-form
                                    layout="horizontal"
                                    ref="formRef"
                                    :model="registerForm"
                                    style="margin-top: 20px"
                                    @finish="onRegisterFinish">
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请设置用户名' },{ message: '用户名已被占用', validator: validateUsername}]">
                                    <a-input v-model:value="registerForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请设置密码' }]">
                                    <a-input-password v-model:value="registerForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item
                                        label="身份"
                                        name="identity"
                                        :rules="[{ required: true, message: '请选择身份' }]">
                                    <a-select v-model:value="registerForm.identity" :options="identityOptions" placeholder="请选择身份"/>
                                </a-form-item>

                                <a-form-item
                                        label="邮箱"
                                        name="email">
                                    <a-input v-model:value="registerForm.email" placeholder="请绑定邮箱">
                                        <template #prefix>
                                            <mail-outlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item>
                                    <a-button :disabled="registerDisabled" type="primary" html-type="submit" style="width: 70%">
                                        注册
                                    </a-button>
                                    <a-button style="margin-left: 5%; width: 25%" @click="() => formRef.resetFields()">
                                        清空
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
            </a-layout-content>
            <a-layout-footer style="background: #000; text-align: center">
                <p style="color:#fff">©{{ new Date().getFullYear() }} {{ systemTitle }}</p>
                <p style="color:#fff">
                    <a @click.prevent="$router.push('/about')">关于</a>&nbsp;|&nbsp;
                    <a>开发团队</a>&nbsp;|&nbsp;
                    <a href="https://gitee.com/shenyang-theone/theone-recsys">了解更多</a>
                </p>
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, toRefs} from "vue";
import {search} from "@/api/post/search";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import globalVariable from "@/components/mathJax/globalVariable";
import {logout as logout_request} from "@/api/post/logout";
import {login} from "@/api/post/login";
import {user_info} from "@/api/post/user_info";
import {notification} from "ant-design-vue";
import {register} from "@/api/post/register";
import {validate_username} from "@/api/post/validate_username";
import {
    DownOutlined,
    UserOutlined
} from "@ant-design/icons-vue";

export default defineComponent({
    components: {
        UserOutlined,
        DownOutlined,
    },
    setup() {
        // -------------onMounted钩子，组件挂载完毕异步加载数据--------------
        onMounted(() => {
            state.login = !store.state.logout;
            state.searchField = $route.query.searchField || 'title';
            state.searchQuery = $route.query.searchQuery || '';
            state.tagsChecked = $route.query.tagsChecked ? JSON.parse($route.query.tagsChecked) : [];
            // 调用搜索接口

            checkLaTex()

            // 处理数据：用于设置悬停样式
            // state.data.forEach((paper) => {
            //     // 区分Title，为每个paper设置单独的isTitleHovered属性
            //     paper.isTitleHovered = false;
            //     paper.authors.forEach((author) => {
            //         // 区分author，为每个author设置单独的isHovered属性
            //         author.isHovered = false;
            //     });
            // });
        });

        // ----------------定义的function，由下至上编写---------------
        const onSearch = () => {
            router.push('/ordinarySearch_demo?searchField='+state.searchField+'&searchQuery='+state.searchQuery+'&tagsChecked='+JSON.stringify(state.tagsChecked.slice()))
        }

        const registerDisabled = computed(() => {
            return !(registerForm.username && registerForm.password && registerForm.identity);
        });

        const validateUsername = (rule, value) => {
            return new Promise((resolve, reject) => {
                if (value.length === 0) {
                    resolve()
                }
                validate_username(value).then((response) => {
                    const { code, message } = response.data.status
                    if (code === 0) {
                        resolve()
                    } else {
                        reject(message)
                    }
                })
            })
        }

        const onRegisterFinish = values => {
            register(values.email, values.username, values.password, values.identity).then((response) => {
                if (response.data.status.code === 0) {
                    //注册成功
                    store.commit('CLEAR_USER_INFO')
                    store.commit('SET_TOKEN', response.data.data)
                    notification['success']({
                        message: '成功',
                        description: '注册成功',
                    })
                    state.loginShow = true;
                    state.registerShow = false;
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })
        }

        const onRegisterShow = () => {
            state.loginShow = false;
            state.registerShow = true;
        };

        const onLoginFinish = values => {
            login(values.username, values.password, values.remember).then((response) => {
                store.commit('CLEAR_USER_INFO')
                store.commit('CLEAR_TOKEN')
                if (response.data.status.code === 0) {
                    state.loginShow = false;
                    state.login = true;

                    store.commit('SET_LOGOUT', false)
                    //成功后继续请求用户信息
                    store.commit('SET_TOKEN', response.data.data)
                    console.log(response.data.data)
                    user_info()
                            .then((response) => {
                                if (response.data.status.code === 0) {
                                    // 成功后设置用户信息
                                    store.commit('SET_USER_INFO', response.data.data.user)
                                    console.log(response.data.data.user)
                                    // if ($route.redirectedFrom) {
                                    //     router.push({
                                    //         path: decodeURIComponent($route.redirectedFrom.fullPath),
                                    //     })
                                    // } else {
                                    //     router.push('/')
                                    // }
                                } else {
                                    notification['error']({
                                        message: '错误',
                                        description: response.data.status.message,
                                    })
                                }
                            })
                            .catch()
                } else if (response.data.status.code === 1 || response.data.status.code === 2) {
                    notification['warning']({
                        message: '登录失败',
                        description: '您提供的用户名或密码无效',
                    })
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })

        };

        const onLoginShow = () => {
            state.loginShow = true;
        };

        const logout = () => {
            state.login = false;
            logout_request()
                    .then((response) => {
                        if (response.data) {
                            //退出成功
                            store.commit('SET_LOGOUT', true)
                            store.commit('CLEAR_USER_INFO')
                            store.commit('CLEAR_TOKEN')
                            // 清空本地存储的数据
                            sessionStorage.clear()
                            // 其他操作...
                        }
                    })
                    .catch(() => {
                        store.commit('SET_LOGOUT', true)
                        store.commit('CLEAR_USER_INFO')
                        store.commit('CLEAR_TOKEN')
                    })
        }

        const onMenuClick = ({ key }) => {
            switch (key) {
                case 'settings': {
                    router.push('/edit_user_profile')
                    break
                }
                case 'favorite': {
                    router.push('/favorite')
                    break
                }
                case 'interest': {
                    router.push('/interest')
                    break
                }
                case 'logout': {
                    logout()
                }
            }
        }

        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        // --------------------定义的vue变量------------------------
        // 确保在使用 '$route' 之前已经声明并初始化了它
        const router = useRouter()
        const $route = useRoute();
        const store = useStore()

        // --------------------定义的响应数据-----------------------
        const state = reactive({
            formRef: null,
            registerShow: false,
            loginShow: false,
            login: true,
            searchOptions: [
                { label: '标题', value: 'title' },
                { label: '摘要', value: 'abstract' },
                { label: '作者', value: 'author' },
                { label: '期刊', value: 'journal' },
            ],
            searchQuery: '',
            searchField: 'title',
            backGroundImg: require('@/assets/background2.png'),
            systemTitle: process.env.VUE_APP_TITLE,
        })

        const registerForm = reactive({
            username: '',
            password: '',
            identity: null,
            email: '',
        });

        const loginForm = reactive({
            username: '',
            password: '',
            remember: false,
        });

        // ----------------------定义的常量--------------------
        const identityOptions = [{
            label: '学生',
            value: '1',
        }, {
            label: '教授',
            value: '2',
        }, {
            label: '副教授',
            value: '3',
        }, {
            label: '讲师',
            value: '4',
        }]

        // ----------------------return函数-------------------
        return {
            onSearch,
            registerDisabled,
            validateUsername,
            identityOptions,
            onRegisterFinish,
            onRegisterShow,
            onLoginFinish,
            onLoginShow,
            onMenuClick,
            ...toRefs(state),
            registerForm,
            loginForm,
        }

    },
})
</script>

<style scoped>
.active {
    background-color: #4F4F4F;
    color: white;
}
.inactive {
    background-color: white;
    color: #4F4F4F;
}

/*分割线*/
.custom-divider {
    border: none;
    height: 1px;
    background-color: #BBBBBB;
}
</style>